<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
       <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.plan_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="info"
                    size="small"
                    plain
                    icon="el-icon-copy-document"
                    @click="handleCopyPlan">复制计划
        </el-button>  
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button
          type="text"
          icon="el-icon-edit-outline"
          size="small"
          v-if="isCreateTask(scope.row)" 
          @click.stop="handleCreateTask(scope.row.id)"
        >生成任务
        </el-button>
      </template>
      
      <template slot-scope="{row}" slot="codeListForm">
        <el-row align="bottom" type="flex">
          <el-col :span="18">
            <el-input
              type="textarea"
              readonly
              :autosize="{ minRows: 3, maxRows: 6}"
              placeholder="请选择车辆列表"
              v-model="row.codeList">
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="text"
                        size="small"
                        plain
                        v-if="formType!='view'"
                        @click="handleSelectVehicle(row)">车队选车
            </el-button>  
            <el-button type="text"
                        size="small"
                        plain
                        v-if="formType!='view'"
                        @click="handleCodeSelectVehicle()">编号选车
            </el-button>  
          </el-col>
        </el-row>
      </template>

    </avue-crud>
    <el-dialog title="车队选车"
        append-to-body
        :visible.sync="vehicleBox"
        :destroy-on-close="true"
        width="345px">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="vehicleFilterText">
        </el-input>
         <el-tree :data="vehicleList"
        show-checkbox
        :default-expand-all="false"
        node-key="id"
        :filter-node-method="filterVehicleNode"
        ref="treeVehicle"
        :default-checked-keys="vehicleTreeObj"
        :default-expanded-keys="vehicleTreeObj"
        :props="{
          children: 'children',
          label: 'title',
          id:'id'
        }">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="vehicleBox = false">取 消</el-button>
        <el-button type="primary"
          @click="selectedVehicles">确 定</el-button>
      </span>
    </el-dialog>    
     <el-dialog title="编号选车"
        append-to-body
        :visible.sync="vehicleCodeBox"
        width="345px">
        <el-input width="80"
          placeholder="从开始编号"
          v-model="vehicleCodeStart"  maxlength="4">
        </el-input>
        ~
        <el-input width="80"
          placeholder="到结束编号"
          maxlength="4"
          v-model="vehicleCodeEnd">
        </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="vehicleCodeBox = false">取 消</el-button>
        <el-button type="primary"
          @click="selectedCodeVehicles">添 加</el-button>
      </span>
    </el-dialog>    

    <el-dialog title="调度计划复制"
                   append-to-body
                   :visible.sync="copyBox"
                   width="500px">
    <el-row >
        <el-col :span="24">
          复制计划日期：
          <el-date-picker
        v-model="copyFromDate"
        type="date"
         value-format="yyyy-MM-dd"
        placeholder="请选择日期">
      </el-date-picker>
      </el-col>
    </el-row>
    <el-row >
      <el-col :span="24">
      生成计划日期：
      <el-date-picker
        v-model="copyToDate"
        type="date"
         value-format="yyyy-MM-dd"
        :picker-options="copyToDateOptions"
        placeholder="请选择日期">
      </el-date-picker>
      </el-col>
    </el-row>
    <br>
    <el-tag type="danger">注：生成计划日期，如果已存在会被替换</el-tag>
          <span slot="footer" class="dialog-footer">
            <el-button @click="copyBox = false">取 消</el-button>
            <el-button type="primary"
                       @click="confirmCopyPlan">确 定</el-button>
          </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove,checkTaskByPlanId,createTaskByPlanId,copyPlan} from "@/api/ems/plan";
  import {getVehicleTree,getVehicleFromCode} from "@/api/ems/vehicle";
  import {mapGetters} from "vuex";
  import website from '@/config/website';
  import {getDate,compareDate} from "@/util/date.js";

  export default {
    data() {
      return {
        vehicleFilterText:"",
        formType:"view",
        form: {},
        query: {},
        loading: true,
        vehicleBox: false,
        vehicleCodeBox:false,
        vehicleCodeStart:"",
        vehicleCodeEnd:"",
        copyBox:false,
        copyFromDate:"",
        copyToDate:"",
        copyToDateOptions: {
          disabledDate: (time) => {
            return time.getTime() < new Date().getTime()
          }
        },
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        vehicleList: [],
        vehicleTreeObj: [],
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          menuWidth: 180,
          searchIndex:3,
          searchIcon:true,     
          defaultSort:{
            prop: 'updateTime',
            order: 'descending'
          },
          column: [
           
            {
              label: "出车日期",
              placeholder:"请输入计划出车日期",
              prop: "planDate",
              type: "date",
              width: 100,
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",              
              search:true,
              editDisabled:true,
              rules: [{
                required: true,
                message: "请输入计划出车日期",
                trigger: "blur"
              }]
            },
            {
              label: "出车时间",
              placeholder:"请输入计划出车时间",
              prop: "planTime",
              width: 80,
              type: "time",
              format: "HH:mm",
              valueFormat: "HH:mm:ss",
              formatter:(val)=>{
                //,value,label
                return val.planTime
              },
              rules: [{
                required: true,
                message: "请输入计划出车时间",
                trigger: "blur"
              }]
            },
             {
              label: "调度状态",
              prop: "status",
              search:true,
              width: 100,
              addDisplay:false,
              editDisplay:false,
              type: "select",
              dicData: [
                {
                  label: "待生成计划",
                  value: 1
                },
                {
                  label: "已生成计划",
                  value: 2
                },
              ],              
              rules: [{
                required: false,
                message: "请输入调度状态",
                trigger: "blur"
              }]
            },
            {
              label: "出车线路",
              prop: "lineId",
              type: "select",
              search:true,
              dicUrl: "/emsapi/blade-ems/line/dict",
              props: {
                label: "name",
                value: "id"
              },
              dataType: "number",
              width: 140,
              slot: true,
              hide: false,
              rules: [{
                required: true,
                message: "请选择出车线路",
                trigger: "blur"
              }]
            },
              
            {
              label: "首站站点",
              prop: "firstStation",
              type: "select",
              search:true,
              hide: true,
              display:false,
              dicUrl: "/emsapi/blade-ems/station/dict",
              props: {
                label: "name",
                value: "id"
              },
              dataType: "number",
              slot: true,
              rules: [{
                required: true,
                message: "请输入首站站点",
                trigger: "blur"
              }]
            },
            {
              label: "自编号",
              prop: "code",
              hide: true,
              search:true,
              display:false,
              placeholder:"请输入车辆自编号",
            },
             {
              label: "调度信息",
              prop: "remark",
              hide: true,
              rules: [{
                required: false,
                message: "请输入调度信息备注",
                trigger: "blur"
              }]
            },
            {
              label: "车辆数量",
              width: 70,
              align:'center',
              addDisplay:false,
              editDisplay:false,
              viewDisplay:false,
              formatter:(row)=>{
                return row.codeList.split(",").length
              },
            },
            {
              label: "车辆列表",
              prop: "codeList",
              slot:true,
              formslot:true,
              span: 24,
              rules: [{
                required: true,
                message: "请选择车辆",
                trigger: "blur"
              }]
            },
            
            {
              label: "调度员",
              prop: "dispatcher",
              search:true,
              addDisplay:false,
              editDisplay:false,
              width: 80,
              rules: [{
                required: false,
                message: "自动录入当前登录用户名称",
                trigger: "blur"
              }]
            },
               {
              label: "更新时间",
              prop: "updateTime",
              search:false,
              addDisplay:false,
              editDisplay:false,
              width: 140,
            },
          
          ]
        },
        data: []
      };
    },
    mounted() {
      // 非租户模式默认加载管理组数据
      if (!website.tenantMode) {
         this.initData(website.tenantId)
      }

      //加载车辆数据
       getVehicleTree().then(res => {
        let newList=[];
        let vehicleList = res.data.data;
        for(let i =0 ;i<vehicleList.length;i++){//第一级为车队
          vehicleList[i].isDept=true;

          if(vehicleList[i].children ){
              let cLen= vehicleList[i].children.length
              let max=50
              if(cLen>max){
                let list= this.splitGroup(Object.assign({},vehicleList[i]),max)
                newList=newList.concat(list)
              }else{
              if(vehicleList[i].children && vehicleList[i].children.length>0)
              {
                  vehicleList[i].title=vehicleList[i].title +"(第"+vehicleList[i].children[0].title+"~"+        
                  vehicleList[i].children[vehicleList[i].children.length-1].title+")"
              } 
                newList.push(vehicleList[i])
              }
          }
          
        }
        this.vehicleList = newList;
        
    });
    },
     watch: {
      vehicleFilterText(val) {
        this.$refs.treeVehicle.filter(val);
      },
      'form.lineId'() {
        if (this.form.lineId !== '') {
          let dic= this.$refs.crud.DIC;
          if(dic.lineId && dic.lineId.length){
            dic.lineId.forEach(ele => {
            if(ele.id==this.form.lineId){
              this.form.lineName=ele.name
            }})
          }
 
        }
    },
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.plan_add, false),
          viewBtn: this.vaildData(this.permission.plan_view, false),
          delBtn: this.vaildData(this.permission.plan_delete, false),
          editBtn: this.vaildData(this.permission.plan_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      isCreateTask(row){
        let v=compareDate(row.planDate,getDate(-1))
        return v==1;
      },
      handleCreateTask(id) {
        checkTaskByPlanId(id).then(res => {
          let status = res.data.data; 
          let msg = res.data.msg; 
          if (status === -1) {
            this.$message.warning(msg);
            return;
          }else if(status === 1){
            msg = msg + "，确定要重新生成吗?"
          }else{
            msg = "确定根据本调度计划生成出车任务及明细吗?"
          }
          this.$confirm(msg, {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            return createTaskByPlanId(id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });

        });
      },  
      handleCopyPlan(){
        this.copyToDate=""
        this.copyFromDate=""
        this.copyBox=true
      },
      confirmCopyPlan(){
        if(this.copyFromDate=="" ){
           this.$message({
            type: "alert",
            message: "复制计划日期不能空!"
          });
          return 
        }
        if(this.copyToDate=="" ){
           this.$message({
            type: "alert",
            message: "生成计划日期不能空!"
          });
          return 
        }
        this.$confirm("确定要复制吗", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            return copyPlan(this.copyFromDate,this.copyToDate);
          })
          .then(() => {
            this.copyBox=false;
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      filterVehicleNode(value, item) {
        if (!value) return true;
        return item.title.indexOf(value) !== -1;
      } ,     
      selectedCodeVehicles(){
        let iStart= parseInt(this.vehicleCodeStart) 
        let iEnd= parseInt(this.vehicleCodeEnd)
        if(iStart>0 && iEnd>0 && iStart< iEnd){
            //加载车辆数据
            getVehicleFromCode(iStart,iEnd).then(res => {
              let vehicleList = res.data.data;

              let ids=(this.form.vehicleIds?this.form.vehicleIds.split(","):[])
              let codes=(this.form.codeList?this.form.codeList.split(","):[])
                //追加方式
                vehicleList.forEach(ele => {
                  if(ids.indexOf(ele.id)==-1){
                      this.vehicleTreeObj.push(ele.id)
                      ids.push(ele.id)
                      codes.push(ele.code)
                  }
                });
              this.form.vehicleIds=ids.join(",")
               this.form.codeList=codes.join(",")
               this.vehicleCodeBox=false
              })
        }else{
            this.$message({
            type: "alert",
            message: "请输入有效编号范围数字!"
          });
        }
      },
      handleCodeSelectVehicle(){
          this.vehicleCodeStart="";
          this.vehicleCodeEnd="";
          this.vehicleCodeBox = true;
      },
    refreshVehicleTree() {
      const vm = this;
      vm.vehicleList = [...vm.vehicleList];
    },
      handleSelectVehicle(row) {
        this.vehicleTreeObj =(row && row.vehicleIds? row.vehicleIds.split(","):[]);
        this.refreshVehicleTree()
        this.vehicleBox = true;
      },
      splitGroup(group,max){
        let list=[];
        let i=0;
        let n=1
        while(i<group.children.length){
          let o =Object.assign({},group)
          let e=(i+max<group.children.length?i+max:group.children.length)
          o.children=group.children.slice(i,  e)
          o.id=o.id+"_"+n
          o.value=o.id
          o.key=o.id
          o.title=o.title+"(第"+group.children[i].title+"~"+group.children[e-1].title+")"
          list.push(o)

          n++
          i=i+max
        }
        return list
      },
      selectedVehicles() {
        let nodes= this.$refs.treeVehicle.getCheckedNodes();
        let ids=[];
        let codes=[];
        nodes.forEach(ele => {
          if(!ele.isDept){
            ids.push(ele.id)
            codes.push(ele.title)
          }
          
        });
        this.vehicleTreeObj=ids
        this.form.vehicleIds=ids.join(",");
        this.form.codeList=codes.join(",");
       this.vehicleBox = false
      },      
      initData(tenantId) {
        // getVehicleTree(tenantId).then(res => {
        //   const column = this.findObject(this.option.column, "vehicleIds");
        //   column.dicData = res.data.data;
        // });
      },     
      
      rowSave(row, done, loading) {

        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {

        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      
      beforeOpen(done, type) {
   
        this.formType=type;//记录最后打开type
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            // if(this.form.hasOwnProperty("vehicleId")){
            //   this.form.vehicleId = this.form.vehicleId.split(",");
            // }            
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
